package com.iris.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Set;

public class SocketClient extends  Thread {
    SocketChannel socketChannel;
    Selector selector;

    @Override
    public void run() {
        try {
            init();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public  void init( ) throws IOException {
        socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        selector = Selector.open();
        if(socketChannel.connect(new InetSocketAddress("localhost",8889))){

        }else{
            socketChannel.register(selector, SelectionKey.OP_CONNECT);
        }
        System.out.println(socketChannel.finishConnect());
        while(true){
            selector.select(1000);
            Set<SelectionKey> sets = selector.selectedKeys();
            if(sets!=null&&sets.size()>0){
                for (SelectionKey set : sets) {
                    if(set.isValid()) {
                        sets.remove(set);
                        SocketChannel sc = (SocketChannel) set.channel();
                        if (set.isConnectable()) {
                            if (sc.finishConnect()) ;
                            else {
                                System.exit(1);
                            }
                        }
                        if (set.isReadable()) {
                            ByteBuffer buffer = ByteBuffer.allocate(1024);
                            int readBytes = sc.read(buffer);

                            if(readBytes>0){
                                buffer.flip();
                                byte[] bytes = new byte[buffer.remaining()];
                                buffer.get(bytes);
                                String result = new String(bytes,"UTF-8");
                                System.out.println("客户端收到消息：" + result);
                            }
                        }
                    }
                }
            }
        }

    }

    public void send(String str) throws IOException {
        socketChannel.register(selector, SelectionKey.OP_READ);
        //将消息编码为字节数组
        byte[] bytes = str.getBytes();
        //根据数组容量创建ByteBuffer
        ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
        //将字节数组复制到缓冲区
        writeBuffer.put(bytes);
        //flip操作
        writeBuffer.flip();
        //发送缓冲区的字节数组
        socketChannel.write(writeBuffer);
    }
}
